package packet

import (
	"encoding/binary"
	"math"

	"gitee.com/ameise84/e3utils/bytes_buffer"
)

func PackBool(w bytes_buffer.UnsafeWriter, data bool) {
	if data {
		_ = w.AppendByte(byte(1))
	} else {
		_ = w.AppendByte(byte(0))
	}
}

func PackUint8(w bytes_buffer.UnsafeWriter, data uint8) {
	_ = w.AppendByte(byte(data))
}

func PackUint16(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data uint16) {
	bs := w.GetTailEmptyBytes()
	order.PutUint16(bs, data)
	w.AddLen(2)
}

func PackUint32(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data uint32) {
	bs := w.GetTailEmptyBytes()
	order.PutUint32(bs, data)
	w.AddLen(4)
}

func PackUint64(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data uint64) {
	bs := w.GetTailEmptyBytes()
	order.PutUint64(bs, data)
	w.AddLen(8)
}

func PackUint(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data uint) {
	PackUint64(w, order, uint64(data))
}

func PackInt8(w bytes_buffer.UnsafeWriter, data int8) {
	PackUint8(w, uint8(data))
}

func PackInt16(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data int16) {
	PackUint16(w, order, uint16(data))
}

func PackInt32(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data int32) {
	PackUint32(w, order, uint32(data))
}

func PackInt64(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data int64) {
	PackUint64(w, order, uint64(data))
}

func PackInt(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data int) {
	PackUint64(w, order, uint64(data))
}

func PackFloat32(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data float32) {
	PackUint32(w, order, math.Float32bits(data))
}

func PackFloat64(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data float64) {
	PackUint64(w, order, math.Float64bits(data))
}

func PackString(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data string) {
	size := len(data)
	PackInt(w, order, size)
	if size > 0 {
		_ = w.AppendString(data)
	}
}

func PackBytes(w bytes_buffer.UnsafeWriter, order binary.ByteOrder, data []byte) {
	size := len(data)
	PackInt(w, order, size)
	if size > 0 {
		_ = w.AppendBytes(data)
	}
}
